package com.example.greetingcard

import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.greetingcard.ui.theme.TipTimeTheme
import java.text.NumberFormat


class TipAccountActivity {

    @Preview(showBackground = true)
    @Composable
    fun TipTimeLayoutPreview() {
        TipTimeTheme {
            TipTimeLayout()
        }
    }

    @Composable
    fun TipTimeLayout() {

        var amountInput by remember { mutableStateOf("") }
        var tipInput by remember { mutableStateOf("") }
        var roundUp by remember { mutableStateOf(false) }
        val amount = amountInput.toDoubleOrNull() ?: 0.0
        val tipPercent = tipInput.toDoubleOrNull() ?: 0.0

        val tip = calculateTip(amount, tipPercent, roundUp)



        Column(
            modifier = Modifier
                .statusBarsPadding()
                .padding(horizontal = 40.dp)
                .safeDrawingPadding()
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text = stringResource(R.string.calculate_tip),
                modifier = Modifier
                    .padding(bottom = 16.dp, top = 40.dp)
                    .align(alignment = Alignment.Start)
            )
            EditNumberField(
                label = R.string.bill_amount,
                keyboardOptions = KeyboardOptions.Default.copy(
                    keyboardType = KeyboardType.Number,
                    imeAction = ImeAction.Next
                ),
                value = amountInput,
                leadingIcon = R.drawable.money,
                onValueChange = { amountInput = it },
                modifier = Modifier.padding(bottom = 32.dp).fillMaxWidth()
            )
            EditNumberField(
                label = R.string.how_was_the_service,
                keyboardOptions = KeyboardOptions.Default.copy(
                    keyboardType = KeyboardType.Number,
                    imeAction = ImeAction.Done
                ),
                value = tipInput,
                leadingIcon = R.drawable.percent,
                onValueChange = { tipInput = it },
                modifier = Modifier.padding(bottom = 32.dp).fillMaxWidth()
            )
            RoundTheTipRow(
                roundUp = roundUp,
                onRoundUpChanged = { roundUp = it },
                modifier = Modifier.padding(bottom = 32.dp)
            )
            Text(
                //text = stringResource(R.string.tip_amount, "$0.00"),
                text = stringResource(R.string.tip_amount, tip),
                style = MaterialTheme.typography.displaySmall
            )
            Spacer(modifier = Modifier.height(150.dp))
        }
    }

    @Composable
    fun EditNumberField(
        // @StringRes 注解是一种类型安全的字符串资源使用方法，用于表明要传递的整数是 values/strings.xml 文件中的字符串资源。
        // 这些注解对于处理代码的开发者以及 Android Studio 中的代码检查工具（如 lint）非常有用。
        @StringRes label: Int,// 指明 label 形参应为字符串资源引用
        @DrawableRes leadingIcon: Int,
        keyboardOptions: KeyboardOptions,
        value: String,
        onValueChange: (String) -> Unit,
        modifier: Modifier = Modifier
    ) {
        // 如果发生状态更改，Compose 会使用新状态重新执行受影响的可组合函数，从而创建更新后的界面。这一过程称为“重组”。Compose 会为您安排重组。
        // Creating a state object during composition without using remember
        // var amountInput by remember { mutableStateOf("") }
        // val amount = amountInput.toDoubleOrNull() ?: 0.0
        // val tip = calculateTip(amount)

        TextField(
            label = { Text(stringResource(label)) },
            singleLine = true,// 将文本框从多行压缩成可水平滚动的单行
            keyboardOptions = keyboardOptions,
            /*KeyboardOptions.Default.copy(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Next
            ),*/// 将键盘类型设置为数字键盘即可输入数字。
            // 使用 KeyboardOptions.Default.copy() 函数，确保使用其他默认选项。
            value = value,
            leadingIcon = { Icon(painter = painterResource(id = leadingIcon), null) },
            onValueChange = onValueChange,
            modifier = modifier
        )
    }

    @Composable
    fun RoundTheTipRow(
        roundUp: Boolean,
        onRoundUpChanged: (Boolean) -> Unit,
        modifier: Modifier = Modifier
    ) {
        Row(
            modifier = modifier
                .fillMaxWidth()
                .size(48.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(text = stringResource(R.string.round_up_tip))
            Switch(
                checked = roundUp,
                onCheckedChange = onRoundUpChanged,
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentWidth(Alignment.End),
            )
        }
    }

    /**
     * Calculates the tip based on the user input and format the tip amount
     * according to the local currency.
     * Example would be "$10.00".
     */
    private fun calculateTip(
        amount: Double,
        tipPercent: Double = 15.0,
        roundUp: Boolean
    ): String {
        var tip = tipPercent / 100 * amount
        if (roundUp) {
            tip = kotlin.math.ceil(tip)
        }
        return NumberFormat.getCurrencyInstance().format(tip)
    }
}